<template>
  <div class="login-container">
    <video class="video" muted="muted" src="../../assets/video/bg-video.mp4" preload="auto" loop="loop" autoplay="true"></video>
    <div class="bg2"></div>
    
    <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" label-width="100px" class="login-loginForm">
      
      <h1>管理系统</h1>
      <i @click="iserweiLogin=!iserweiLogin;sms=false" :class="['jiaobiao','iconfont',iserweiLogin?'icon-diannaojiaobiao':'icon-erweimajiaobiao']"></i>
      <!-- 常规登录 -->
      <div class="common-login" v-if="!iserweiLogin&&!sms">
        <el-form-item label="用户名" prop="username">
           <el-input type="text" v-model="loginForm.username" autocomplete="off"></el-input>
        </el-form-item>
      
        <el-form-item label="密码" prop="password">
           <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
        </el-form-item>
      
        <el-form-item label="验证码" prop="captcha">
           <el-input maxlength="5" class="captcha" ref="captcha" v-model="loginForm.captcha" @keydown.native.enter="submitForm('loginForm')"></el-input>
           
           <span @click="updateCaptcha" class="captcha-svg" v-html="captchaSvg"></span>
        </el-form-item>
      
        <el-form-item>
           <el-button type="primary" @click="submitForm('loginForm')">提交</el-button>
        
        </el-form-item>
        <el-form-item>
          <div class="sms" @click="sec">
            <span class="iconfont icon-iphone" @click="sms=true;iserweiLogin=true">短信登入</span>
          </div>     
        </el-form-item>
      </div>
      <!-- 二维码登录 -->
      <div class="erwei" v-else-if="!sms && iserweiLogin">
        <div class="img">
           <img :src="qrDataUrl" alt="" width="200px">
           <i class="mask" :style="qrStyle" @click="getQrcode" v-show="isScanCodeSuccess"></i>
        </div>
        
        <p>请用微信扫码登录</p>
      </div>
      <!-- 手机验证码登入 -->
      <div class="smsContainer" v-else>
         <el-form-item label="手机号" prop="phoneNumber">
            <el-input maxlength="11" v-model="phoneNumber" class="captcha phone"></el-input>
            <button @click="sendSmsCode" :disabled="disabled" class="captcha-svg" :style="phoneStyle">{{context}}</button>
         </el-form-item>
         <el-form-item label="验证码" prop="smsCode">
          <el-input v-model="smsCode"></el-input>
         </el-form-item>
         <el-form-item>
          <el-button type="primary" @click="smsSubmit">提交</el-button>
         </el-form-item>
      </div>
      

    </el-form>
  </div>
</template>
<script src="../../utils/倒计时.js"></script>
<script>
// 引入api中的方法
import * as api from "../../api";
// 引入辅助函数
import {mapMutations} from "vuex";
// 引入socket.io
// 引入生成二维码的插件qrcode
import io from "socket.io-client";
import qrcode from "qrcode";
// 引入扫码成功和失效的图片
import codeSuccessImg from "../../assets/img/scancode.png";
import codeInvalidImg from "../../assets/img/invalidQr.png";
export default {
  data() {
    var validateCaptcha = (rule, value, callback) => {
        //callback只要传参了，表示表单验证不通过；不传参表示表单验证通过
        //rule是个对象，验证对象
        //value是input中输入的内容
        if(value.length!==5){
            callback("验证码必须是5位")
        }else{
            callback()
        }
      
    };
    var validateUsername = (rule, value, callback) => {
        //callback只要传参了，表示表单验证不通过；不传参表示表单验证通过
        //rule是个对象，验证对象
        //value是input中输入的内容
        var reg = /^\w{3,12}$/
        
        if(reg.test(value)){
            //验证通过
            callback()
        }else{
            callback("用户名必须是数字字母下划线,3-12位")
        }
      
    };
    var validatePass = (rule, value, callback) => {
        //callback只要传参了，表示表单验证不通过；不传参表示表单验证通过
        //rule是个对象，验证对象
        //value是input中输入的内容
        if(value.length<3){
            callback("密码不能少于3位")
        }else{
            callback()
        }
      
    };
    return {
      iserweiLogin:false, //是否二维码登录
      captchaSvg:"",//验证码
      qrDataUrl:"",//二维码base64的图片地址
      isScanCodeSuccess:false,//是否扫码成功
      phoneNumber:"",//手机号
      smsCode:"",//短信验证码
      sms:false,//短信登入
      context:"点击发送验证码",//button中的内容
      disabled:false,//禁用手机验证码按钮
      totalTime:59,//倒计时
      //点击发送验证码样式
      phoneStyle:{
        color: '#888',
        'line-height': '45px',
        'text-decoration': 'underline',
      },
      loginForm: {//登入输入框数据
        username: "",
        password: "",
        captcha: "",
      },
      rules: {//表单验证规则
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
      qrStyle:{
        backgroundImage:`url(${codeSuccessImg})`
      }
    };
  },
  created(){
    // console.log(process.env.VUE_APP_BASE_URL);
    //调用获取验证码的方法
    this.updateCaptcha()
  },

  methods: {
    sec(){
      let totalTime = localStorage.getItem("time");
      let sec = null;
      if (totalTime) {
        //本地有
        // console.log(1111);
        this.disabled = true;
        sec = parseInt((totalTime - +new Date()) / 1000);
        // console.log(sec);
        if (sec > 0) {
          this.context = sec + "s后重新发送";
          let timer = setInterval(() => {
            console.log(sec);
            sec--;
            this.context = sec + "s后重新发送";
            if (sec == 0) {
              // 重置倒计时时间
              this.disabled = false;
              this.context = "点击发送验证码";
              clearInterval(timer);
            }
          }, 1000);
        } else {
          this.disabled = false;
        }
      }


    },
    //发送手机验证码
    sendSmsCode(){
      // console.log(1);//测试
      api.getSmsCode(this.phoneNumber)
      .then(res=>{
        console.log(res);
        if(res.data.state){
          this.$message.success("短信发送成功")
          this.disabled = true;
          let time = +new Date() + 59 * 1000;
          localStorage.setItem("time", time);
          // 短信验证码倒计时
          this.context = "60s后重新发送";
          let timer = setInterval(() => {
            this.context = this.totalTime + "s后重新发送";
            this.totalTime--;
            if (this.totalTime < 0) {
              // 重置倒计时时间
              this.totalTime = 59;
              this.context = "重新发送验证码";
              clearInterval(timer);
            }
          }, 1000);
        }else{
          this.$message.error("短信发送失败")
        }
      });

    },
    smsSubmit(){
      const loading = this.$loading({
          lock:true,
          text:"正在登入",
          spinner:"el-icon-loading",
          background:"rgba(0,0,0,0.7)"
      });
      // console.log(2);
      api.loginApi(null,null,{type:"sms"},this.smsCode)
      .then(res=>{
        console.log(res);
        if(res.data.state){
          loading.close()
          this.$message.success({
            message:"登入成功,正在跳转",
            type:"success",
            duration:1000
          });
          //登入成功
          //1.将token储存到本地
          localStorage.setItem("qf-token", res.data.token);
          //2.将userInfo存到本地
          localStorage.setItem(
            "qf-userInfo",
            JSON.stringify(res.data.userInfo)
          );
          //按钮权限
          localStorage.setItem(
            "permissionButtons",
            JSON.stringify(res.data.permission.buttons)
          );
          //3.将用户信息添加到vuex
          this.SET_USER_INFO(res.data.userInfo);
          //4.跳转到主页
          this.$router.push("/");
        } else {
          loading.close();
        }

      })
      

    },
    //封装一个获取二维码地址的方法
    getQrcode(){
      // 关闭qrcode遮罩
      this.isScanCodeSuccess = false
      //让遮罩的样式初始化
      this.qrStyle.backgroundImage = `url(${codeSuccessImg})`
      //从本地拿出sid
      let sid = localStorage.getItem("qf-sid");
      console.log(sid);
      if(!sid){
        this.$message.error("没有sid")
        return
      }
      api.getQrcodeUrlApi(sid)
      .then(res=>{
        console.log(res);
        let qrUrl = res.data.scanCodeUrl;
        //通过qrcode将二维码地址生成二维码
        qrcode.toDataURL(qrUrl,(err,dataUrl)=>{
           //console.log(dataUrl);
           //关掉qrcode的遮罩
           this.isScanCodeSuccess = false;
           this.qrDataUrl = dataUrl
        })

      })
    },
    ...mapMutations(["SET_USER_INFO"]),
    //封装一个方法，专门用于获取验证码
    updateCaptcha(){
      api.getCaptchaApi()
      .then(res=>{
        // console.log(res.data);
        this.captchaSvg = res.data.img
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        // 所有表单验证通过之后，那么valid的值为true 否则为false

        // 1.先校验本地的表单是否通过
        // 2.校验验证码是否正确
        // 3.校验用户名密码是否正确

        if (valid) {//表单验证通过
          // 打开loading动画
          const loading = this.$loading({
            lock:true,
            text:"正在登入",
            spinner:"el-icon-loading",
            background:"rgba(0,0,0,0.7)"
          });
          //验证码校验 把用户输入的验证码转成小写
          api.verifyCaptcha(this.loginForm.captcha.toLowerCase())
          .then(res=>{
            console.log(res);
            if(res.data.state){//验证码正确
              //继续校验用户名和密码
              api.loginApi(this.loginForm.username,this.loginForm.password)
              .then(res=>{
                console.log(res);
                if(res.data.state){//登入成功
                   loading.close() //关闭加载动画
                   this.$message.success({
                     message:"登入成功,正在跳转",
                     type:"success",
                     duration:1000
                   });
                   //1.将token存到本地
                   localStorage.setItem("qf-token",res.data.token)
                   //2.将userInfo存到本地
                   localStorage.setItem("qf-userInfo",JSON.stringify(res.data.userInfo))
                   //按钮权限
                   localStorage.setItem("permissionButtons",JSON.stringify(res.data.permission.buttons))
                   //3.将用户信息添加到vuex
                   this.SET_USER_INFO(res.data.userInfo)
                   //4.跳转到主页 用编程式导航
                   this.$router.push("/")
                }else{//登录失败
                  // alert("账户或密码错误")
                  loading.close()
                  this.$message.error("账户或密码错误")
                }
              })

            }else{
              // 验证码错误
              // console.log("验证码错误");
              // 关闭动画
              loading.close()
              this.$message.error("验证码错误")
              //清空验证码输入框的内容
              this.loginForm.captcha = ""  
              //让验证码输入框重新获得焦点
              this.$refs.captcha.focus()                        
              // 刷新验证码
              this.updateCaptcha()
            }
          })
          
        } else {//表单验证不通过
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  watch:{//监听切换二维码登录这个字段
    iserweiLogin(newVal,oldVal){
      // console.log(newVal);
      if(newVal){//已经切换二维码登录
         //1.通过socket.io和服务器建立socket连接
         let socket = io("ws://chst.vip");
         //2.监听socket连接成功事件，发送请求，请求"users/getScanCode"获取二维码地址
         socket.on("connectSuccess",(data)=>{
             //console.log(data);
             //将sid存到本地
             let {sid} = data //将sid解构出来
             localStorage.setItem("qf-sid",sid);
             //3.获取二维码地址，生成二维码图片
             this.getQrcode()
            
         })
         //4.用户扫描二维码
         //5.监听socket事件，scancodeSuccess(这个事件不是socket.io定义的，是前后端约定的)，获取到wechatCode
         socket.on("scancodeSuccess",(data)=>{
            //console.log("扫码成功");
            //console.log(data);
            //6.请求users/wechatLogin,传递wechatCode
            if(data.state){//扫码成功
               //显示遮罩
               this.isScanCodeSuccess = true;
               api.wechatLoginApi(data.wechatCode)
               .then(res=>{
                  if(res.data.state){//登入成功
                     console.log(res);
                     //将用户信息和token储存起来
                     //1.将token储存到本地
                     localStorage.setItem("qf-token",res.data.token)
                     //2.将userInfo存到本地
                     localStorage.setItem("qf-userInfo",JSON.stringify(res.data.userInfo))
                     //3.将用户信息添加到vuex
                     this.SET_USER_INFO(res.data.userInfo)
                     //按钮权限
                     localStorage.setItem("permissionButtons",JSON.stringify(res.data.permission.buttons))
                     //4.跳转到首页
                     this.$router.push("/")
                  }else{
                    this.$message.error("微信登入失败")
                  }
                  
               })
            }else{
              this.$message.error("扫码失败")
            }
            //7.判断成功和失败
         })
         socket.on("invalidCode",data=>{
           console.log(data);
           this.qrStyle.backgroundImage = `url(${codeInvalidImg})`//失效的图片
           this.isScanCodeSuccess = true; //遮罩显示
         })
         
         

      }else{
        //切换成了普通登录
        //二维码遮罩关闭
        this.isScanCodeSuccess=false;
      }

    }
  }
};
</script>
<style scoped lang="less">
.video{
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
}
.bg2{
    background-image:url("../../assets/img/bg.png");
    background-repeat:no-repeat;
    background-size:100% 100%;
    width:20%;
    height:40%;
    position:fixed;
    left:10%;
    top:25%;
    opacity:.5;
}
.login-loginForm{
    position:fixed;
    left:65%;
    top:20%;
    border-radius:5px;
    width:400px;
    height:480px;
    padding:30px 26px 0 0;
    background:rgba(0,0,0,0.3);
    
    h1{
        text-align:center;
        color:#fff;
        padding:30px 0;
    }
    .jiaobiao{
        font-size:60px;
        color:#fff;
        position:absolute;
        top:-1px;
        right:-1px;
        opacity: .7;
        cursor:pointer;
    }
    .el-input{
        width:250px;
    }
    .el-button--primary{
        width:250px;
        background:linear-gradient(90deg,#1596fb,#002dff);
    }
    /deep/.el-form-item__label{
        color:#fff;
    }
    .captcha {
			width: 100px;
      height:45px;
			vertical-align: top;
			/deep/.el-input__inner {
				width: 100%;
				height: 45px;
				border-radius: 5px 0 0 5px;
				border: 0;
				font-size: 18px;
			}
		}
		.captcha-svg {
			background: #fff;
			display: inline-block;
			height: 45px;
			width: 150px;
			text-align: center;
			cursor: pointer;
			border: 0;
			border-radius: 0px 5px 5px 0;
		}

    .erwei{
        .img{
          display: inline-block;
		      position: relative;
		      width: 200px;
		      height: 200px;
          img{
            position: absolute;
			      left: 55%;
          }
        }
        .mask {
			    width: 100%;
			    height: 100%;
			    opacity: 0.8;
			    background-color: #fff;
			    position: absolute;
			    left: 55%;
			    // background-image: url("../../assets/img/scancode.png");
			    background-size: 50%;
			    background-repeat: no-repeat;
			    background-position: center;
			    cursor: pointer;
		    }
        p{
            text-align:center;
            padding-top:10px;
            font-size:15px;
            color:#fff;
        }       
  }
  // 手机验证码登入
  .smsContainer {
  padding-right: 20px !important;
  width: 89%;

  /deep/ .el-form-item__label {
    // margin-left: 80px !important
    padding: 0 !important;
    padding-right: 10px !important;
  }

  /deep/ .phone {
    width: 140px !important;
  }

  /deep/ .captcha-svg {
    width: 115px !important;
  }

  /deep/ .el-form-item__content {
    margin: 0;
  }
}
      
}
// 切换短信登入字段
.icon-iphone{
  padding-left:70px;
  text-decoration:underline;
  cursor:pointer;
}
// 手机验证码字段
.login-loginForm .captcha-svg[data-v-247e7dd8]{
  text-align:right;

}



</style>
